package cn.tom.tools;


import cn.tom.dao.RoleDao;
import cn.tom.entity.Role;
import cn.tom.entity.XUser;
import cn.tom.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Component
public class TokenAndUser {

    private static Logger log = LoggerFactory.getLogger(TokenAndUser.class);

    @Resource(name = "userServiceImpl")
    private   UserService userService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RoleDao roleDao;

    private static  UserService userService2 ;
    private static  RedisTemplate redisTemplate2 ;
    private static RoleDao roleDao2;

    @PostConstruct
    private void init(){
        userService2 = userService;
        redisTemplate2 = redisTemplate;
        roleDao2 = roleDao;
    }


    public  static XJson findOne(){
        Integer uid =(Integer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("util"+uid);
        if (uid==null)      return XResp.pack(501,"没有登录或登录超时","");
        XUser userInfo =(XUser) redisTemplate2.opsForHash().get("userInfo", uid);
        if (userInfo == null){
            userInfo = getUserInfo(uid);
            redisTemplate2.opsForHash().put("userInfo",userInfo.getId(),userInfo);
        }
        System.out.println(1);
        return  XResp.pack(200,"",userInfo);
    }

    public  static XJson ifToken(HttpServletRequest request){
        System.out.println("ifToken");
        String bearer = request.getHeader("Authorization");
        if(bearer == null || bearer.length() < 7) return XResp.pack(403,"请登录......",null);
        String token = bearer.substring(7);
        if(JwtUtil.isValid(token) == false)return XResp.pack(403,"Token 被篡改或过期",null);
        Integer uid = JwtUtil.getUid(token);
        XUser user = getUserInfo(uid);
        if(!user.getRoles().contains("usr"))return XResp.pack(403,"非法用户......",null);
        if (user==null)throw new UsernameNotFoundException("账号不存在");
        return XResp.pack(200,"",user);
    }
    private static XUser getUserInfo(Integer uid){
        XUser user =(XUser) redisTemplate2.opsForHash().get("userInfo", uid);
        if (user == null){
            user = userService2.findById(uid);
            List<String> roles = getUserRole(uid);
            user.setRoles(roles);
            redisTemplate2.opsForHash().put("userInfo",uid,user);
        }
        return user;
    }

    private static List<String>  getUserRole(Integer uid){
        List<String> roles = (List<String>) redisTemplate2.opsForHash().get("userRole",uid);
        if (roles == null){
            roles = new ArrayList<>();
            // 如果没有创建对象
            List<Integer> roleIds = roleDao2.findByUidRoles(uid);
            for (Integer roleId : roleIds) {
                Role role =(Role) redisTemplate2.opsForHash().get("role", roleId);
                if (role == null){
                    role = roleDao2.findByRoleId(roleId);
                    redisTemplate2.opsForHash().put("role",role.getId(),role);
                }
                roles.add(role.getRoleName());
                // 储存角色信息
                redisTemplate2.opsForHash().put("userRole",uid,roles);
            }
            // 最后将用户角色信息储存进Redis中 方便下次获取
        }
        return roles;
    }


}
